﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using SharedLib.Helpers;

namespace TracyGUI.Model
{
    class ViewStateManager
    {
        private string ViewStateFileName{
            get { return AppDataHelper.GetAppDataFile("ViewState.xml"); }
        }
        private XmlDocument _doc;
        private XmlDocument Doc
        {
            get
            {
                if (_doc == null)
                {
                    _doc = new XmlDocument();
                    if (File.Exists(ViewStateFileName))
                    {
                        _doc.Load(ViewStateFileName);
                        
                    }
                }
                return _doc;
            }
        }

        private XmlElement _rootNode;
        private XmlElement RootNode
        {
            get
            {
                if (_rootNode == null)
                {
                    _rootNode = Doc.SelectSingleNode("/view-states") as XmlElement;
                    if (_rootNode == null)
                    {
                        _rootNode = Doc.CreateElement("view-states");
                        Doc.AppendChild(_rootNode);
                    }
                }
                return _rootNode;
            }
        }

        public void LoadViewState(IHasViewState controller)
        {
            LoadViewState(controller, RootNode);
        }

        public void LoadViewState(IHasViewState controller, XmlElement parentNode)
        {
            XmlElement viewStateNode = parentNode.SelectSingleNode(String.Format("view-state[@controller='{0}']", controller.GetType().Name)) as XmlElement;
            if (viewStateNode != null) controller.LoadViewState(this, viewStateNode);
        }

        public XmlElement SaveViewState(IHasViewState controller, XmlNode parentNode)
        {
            XmlElement viewStateNode = Doc.CreateElement("view-state");
            viewStateNode.SetAttribute("controller", controller.GetType().Name);
            controller.SaveViewState(this, viewStateNode, Doc);
            parentNode.AppendChild(viewStateNode);
            return viewStateNode;
        }
        public void SaveViewState(IHasViewState controller)
        {
            XmlElement originalViewStateNode = RootNode.SelectSingleNode(String.Format("view-state[@controller='{0}']", controller.GetType().Name)) as XmlElement;
            if (originalViewStateNode != null) RootNode.RemoveChild(originalViewStateNode);
            SaveViewState(controller, RootNode);
        }

        public void SaveToFile()
        {
            _doc.Save(ViewStateFileName);
        }
    }
}
